package cn.briarbear.myblog.controller;

import cn.briarbear.myblog.entity.table.Blog;
import cn.briarbear.myblog.entity.vo.BlogView;
import cn.briarbear.myblog.entity.vo.TagView;
import cn.briarbear.myblog.enums.ViewConsts;
import cn.briarbear.myblog.service.IBlogService;
import cn.briarbear.myblog.service.ITagBlogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

@Controller
public class BlogController {

    private final static Logger logger = LoggerFactory.getLogger(BlogController.class);

    @Autowired
    private IBlogService blogService;

    @Autowired
    private ITagBlogService tagBlogService;

    @Autowired
    private CacheManager cacheManager;

    @GetMapping("/blog")
    public String getAllBlogView(Model model,Integer tagId){
        List<BlogView> blogViewList = new ArrayList<>();

        if (tagId != null){
            blogViewList = blogService.getBlogByTagId(tagId);
        }else {
            blogViewList = blogService.getAllBlogView();
        }

        //获取所有标签视图
        List<TagView> tagViews = tagBlogService.getAllTagView();

        //添加博客到model中
        model.addAttribute(ViewConsts.VIEW_BLOGLIST,blogViewList);
        model.addAttribute(ViewConsts.VIEW_TAGLIST,tagViews);

        return "blogs";

    }

    @GetMapping("/blog/{id}")
    public String getBlogById(Model model, @PathVariable Integer id){
        Blog blog = blogService.getBlogById(id);
        BlogView blogView = new BlogView(blog);
        model.addAttribute(ViewConsts.VIEW_BLOG,blogView);
        return "blogInfo";
    }


    @GetMapping("/search")
    public String blogSearch(Model model, @RequestParam String keyword){

        logger.info("查询关键字="+ keyword);

        List<BlogView> blogViewList = blogService.searchBlogByKeyword(keyword);
        //获取所有标签视图
        List<TagView> tagViews = tagBlogService.getAllTagView();
        model.addAttribute(ViewConsts.VIEW_TAGLIST,tagViews);
        model.addAttribute(ViewConsts.VIEW_BLOGLIST,blogViewList);

        return "blogs";
    }
}
